﻿using System.Collections.Generic;

namespace exercise.栈
{
    public class Solution
    {
        public bool IsValid(string s)
        {
            Stack<char> stack = new Stack<char>();
            foreach (char c in s.ToCharArray())
            {
                if (c == '(' || c == '{' || c == '[')
                {
                    stack.Push(c);
                }
                else
                {
                    // 匹配右括号，成功则消除

                    if (stack.Count > 0)
                    {
                        char left = stack.Peek();
                        char right = leftOf(c);
                        if (left == right)
                        {
                            stack.Pop();
                        }
                    }
                    else
                    {
                        //和最近的左括号不匹配
                        return false;
                    }
                }
            }

            return stack.Count == 0;
        }
        char leftOf(char c)
        {
            if (c == '}') return '{';
            if (c == ')') return '(';
            return '[';
        }
    }
}
